<template>
  <div class="table-gl-w">
    <a-tabs @change="changeStatus" size="mini">
      <a-tab-pane v-for="tab in tabsList" :key="tab.key">
        <template #title>
          <span>{{ tab.title }}</span>
          <span v-if="tab.key || tab.key === 0">({{ countMap[tab.key] || 0 }})</span>
        </template>
      </a-tab-pane>
    </a-tabs>
    <div class="search-w table-filter-form">
      <FilterTable :filterItem="filterItem" :isReset="true" @search="searchByVal" />
    </div>
    <div class="table-gl-con">
      <TableWrap style="flex: 1" @refresh="getTableList">
        <template #tableBody>
          <a-table class="table-singe-line show-border-table" ref="tableListref" :span-method="spanMethodAll" row-key="id" :expandable="expandable" :default-expand-all-rows="true" :loading="tableLoading" @selection-change="selectColumn" :row-selection="rowSelection" :columns="tableColumns" :data="tableList" size="mini" :pagination="false" :scroll="{ x: 1600, y: '100%' }">
            <template #columns>
              <a-table-column v-for="(item, index) of tableColumns" :fixed="item.fixed" :key="index" :align="item.align" :width="item.width" :title="item.title" :data-index="item.dataIndex">
                <template v-if="item.tip" #title>
                  <a-popover>
                    <template #content>
                      <p style="max-width: 400px">{{ item.tip }}</p>
                    </template>
                    <p>
                      <span>{{ item.title }}</span>
                      <icon-question-circle />
                    </p>
                  </a-popover>
                </template>
                <template v-if="item.dataIndex == 'sort'" #cell="{ rowIndex }">
                  <p>{{ rowIndex + 1 }}</p>
                </template>
                <template v-else-if="item.dataIndex == 'img'" #cell="{ record }">
                  <div class="flex-c-sb" style="padding-right: 20px">
                    <div class="order-w flex">
                      <div class="order-detail-item" style="width: 200px">
                        <div class="flex-c">
                          <span class="label">采购订单：</span>
                          <span class="highlight cursor" @click="toDetail(record)">{{ record.billNo }}</span>
                          <CopyText class="popup-edit-icon-hover" style="margin-left: 5px" :val="record.billNo" />
                        </div>
                      </div>
                      <div class="order-detail-item" style="width: 200px">
                        <p><span class="label">采购方：</span>{{ record.companyName }}</p>
                      </div>
                      <div class="order-detail-item" style="width: 120px">
                        <p><span class="label">结算方式：</span>{{ settleAccounts[record.settleType] }}</p>
                      </div>
                      <div class="order-detail-item" style="width: 120px">
                        <p><span class="label">采购员：</span>{{ record.purchaseUname }}</p>
                      </div>
                      <div class="order-detail-item" style="width: 200px" v-if="record.status == 20 || record.status == 30">
                        <p><span class="label">提交时间：</span>{{ $setTime(record.gmtAudit, 'YYYY/MM/DD HH:mm') }}</p>
                      </div>
                      <div class="order-detail-item" style="width: 200px" v-if="record.status == 30">
                        <p><span class="label">接单时间：</span>{{ $setTime(record.gmtAccept, 'YYYY/MM/DD HH:mm') }}</p>
                      </div>
                      <div class="order-detail-item" style="width: 200px" v-if="record.status == 40">
                        <p><span class="label">完成时间：</span>{{ $setTime(record.gmtFinished, 'YYYY/MM/DD HH:mm') }}</p>
                      </div>
                      <template v-if="record.status == 21">
                        <div class="order-detail-item" style="width: 120px">
                          <p><span class="label">拒单人：</span>{{ record.acceptUname }}</p>
                        </div>
                        <div class="order-detail-item" style="width: 200px">
                          <p><span class="label">拒单时间：</span>{{ $setTime(record.gmtAccept, 'YYYY/MM/DD HH:mm') }}</p>
                        </div>
                        <div class="order-detail-item flex-c warningColor" style="width: 200px; line-height: 1">
                          <div class="flex-c">
                            <icon-exclamation-circle :size="14" />
                            <span>拒单原因：</span>
                          </div>
                          <TextLimit style="flex: 1; line-height: 1" class="warningColor" :val="record.auditRemark" :rows="1" />
                        </div>
                      </template>
                    </div>
                    <div class="flex-c">
                      <a-space>
                        <a-tag color="arcoblue" size="small" bordered>{{ statusMap[record.status] }}</a-tag>
                        <div style="width: 70px">
                          <a-button v-if="record.status === 20 && $authPass('procurement.purchase.receive')" type="text" @click="openReceive(record)" size="mini">接单/拒单</a-button>
                          <a-button v-else type="text" @click="toDetail(record)" size="mini">详情</a-button>
                        </div>
                      </a-space>
                    </div>
                  </div>
                </template>
              </a-table-column>
            </template>
            <template #expand-row="{ record }">
              <a-table class="table-singe-line" row-class="child-row" :show-header="false" row-key="id" :bordered="false" :columns="tableColumns" :data="record.billItems" size="mini" :pagination="false">
                <template #columns>
                  <a-table-column :width="10" />
                  <a-table-column :width="40" />
                  <a-table-column v-for="(item, index) of tableColumns" :key="index" :fixed="item.fixed" :align="item.align" :width="item.width" :title="item.title" :data-index="item.dataIndex">
                    <template v-if="item.dataIndex == 'sort'" #cell> </template>
                    <template v-else-if="item.dataIndex == 'img'" #cell="option">
                      <ImgPopover :src="option.record.productImg">
                        <template #con>
                          <a-image width="40" height="40" fit="contain" :src="option.record.productImg" />
                        </template>
                      </ImgPopover>
                    </template>
                    <template v-else-if="item.dataIndex == 'productName'" #cell="option">
                      <TextLimit :val="option.record.productName" :rows="2" />
                    </template>
                    <template v-else-if="item.dataIndex == 'sku'" #cell="option">
                      <p class="highlight cursor" @click="toDetailItem(option.record)">{{ option.record.sku }}</p>
                      <div class="urgent" v-show="option.record.urgent">急</div>
                    </template>
                    <template v-else-if="item.dataIndex == 'productSpecs'" #cell="option">
                      <TextLimit :val="getProductSpecs(option.record)" />
                    </template>
                    <template v-else-if="item.dataIndex == 'remark'" #cell="option">
                      <TextLimit :val="option.record.remark || '--'" :rows="2" />
                    </template>
                    <template v-else-if="item.dataIndex == 'gmtExpectDelivery'" #cell="option">
                      <p>{{ $setTime(option.record.gmtExpectDelivery, 'YYYY/MM/DD') }}</p>
                    </template>
                    <template v-else-if="['materialPrice', 'productPrice', 'laborPrice'].includes(item.dataIndex)" #cell="option">
                      <p>￥{{ option.record[item.dataIndex] }}</p>
                    </template>
                    <template v-else-if="item.dataIndex == 'rate'" #cell="option">
                      <p>{{ option.record.rate }}%</p>
                      <p class="highlight">{{ option.record.priceType == 1 ? '含税' : '不含税' }}</p>
                    </template>
                  </a-table-column>
                </template>
              </a-table>
            </template>
          </a-table>
        </template>
      </TableWrap>
      <div class="pagination-footer">
        <a-pagination size="mini" :total="total" :default-page-size="searchVal.pageSize" :current="searchVal.pageNum" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size @page-size-change="sizeChange" @change="changePage" />
      </div>
    </div>
  </div>
  <!-- 采购单详情 -->
  <PurchaseOrderDetail v-if="showDetail" :isShow="showDetail" source="supplier" :currentId="currentData.id" @closed="showDetail = false" />
  <!-- 采购单明细详情 -->
  <PurchaseOrderItemDetail v-if="showItemDetail" :isShow="showItemDetail" source="supplier" :currentItem="currentData" @closed="showItemDetail = false" />
  <!-- 采购单接单 -->
  <PurchaseOrderReceive v-if="showReceive" :isShow="showReceive" source="supplier" :currentId="currentData.id" @closed="showReceive = false" @success="getListAndCount" />
</template>

<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import { FilterTableItem } from '@/types/components'
  import FilterTable from '@/components/TableFilter.vue'
  import PurchaseOrderDetail from '../components/purchaseOrderDetail.vue'
  import PurchaseOrderReceive from '../components/purchaseOrderReceive.vue'
  import PurchaseOrderItemDetail from '../components/purchaseOrderItemDetail.vue'
  import { findPurchaseBySupplierPage, findPurchaseCountStatusBySupplier } from '@/api/purchaseApplication'

  import { parseJson } from '@/utils'

  onMounted(() => {
    getListAndCount()
  })
  const tableColumns: Array<any> = [
    {
      title: '序号',
      dataIndex: 'sort',
      width: 40,
    },
    {
      title: '图片',
      dataIndex: 'img',
      width: 60,
    },
    {
      title: '产品名称',
      dataIndex: 'productName',
      width: 100,
    },
    {
      title: 'SKU',
      dataIndex: 'sku',
      width: 100,
    },
    {
      title: 'SKU规格',
      dataIndex: 'productSpecs',
      width: 100,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      width: 100,
    },
    {
      title: '期望交期',
      dataIndex: 'gmtExpectDelivery',
      width: 85,
    },
    {
      title: '采购数量',
      dataIndex: 'purchaseAmt',
      width: 85,
    },
    {
      title: '截单数量',
      tip: '终止采购单还未交货的数量',
      dataIndex: 'cutoffAmt',
      width: 85,
    },
    {
      title: '交货中数',
      tip: '已交货还未签收的数量',
      dataIndex: 'deliveringAmt',
      width: 85,
    },
    {
      title: '实际交货数',
      tip: '实际收到的数量',
      dataIndex: 'deliveryRealAmt',
      width: 95,
    },
    {
      title: '实收材质重量(g)',
      dataIndex: 'materialRealWeight',
      width: 110,
    },
    {
      title: '材质单价(元/g)',
      dataIndex: 'materialPrice',
      width: 100,
    },
    {
      title: '产品单价',
      dataIndex: 'productPrice',
      width: 85,
    },
    {
      title: '工费单价',
      tip: '工费：这里的工费单价是指供应商报价的组成部分，有些供应商的报价是不含工费的或者工费是包含在产品单价的，则为空。',
      dataIndex: 'laborPrice',
      width: 85,
    },
    {
      title: '税率',
      dataIndex: 'rate',
      width: 80,
    },
  ]
  const expandable = ref<any>({
    title: '',
    defaultExpandAllRows: true,
    expandedRowKeys: [],
    width: 10,
  })
  const tabsList = [
    { key: '', title: '全部' },
    { key: 20, title: '待接单' },
    { key: 21, title: '已拒单' },
    { key: 30, title: '采购中' },
    { key: 40, title: '已完成' },
  ]
  const statusMap = {
    0: '已作废',
    1: '草稿中',
    10: '待审核',
    11: '已驳回',
    20: '待接单',
    21: '已拒单',
    30: '采购中',
    40: '已完成',
  }
  const filterItem = ref<Array<FilterTableItem>>([
    {
      type: 'input_keyword',
      key: 'billNos',
      keyItems: [{ label: '采购单号', value: 'billNos' }],
      keyWidth: '110',
      value: ref(),
      placeholder: '请输入',
      label: '',
      width: 160,
      isMultiple: true,
    },
    {
      type: 'input_keyword',
      key: 'skus',
      keyItems: [
        { label: 'SKU', value: 'skus' },
        { label: '产品名称', value: 'productName' },
      ],
      keyWidth: '100',
      value: ref(),
      placeholder: '请输入',
      label: '',
      width: 160,
      isMultiple: true,
    },

    {
      key: 'companyName',
      label: '采购方',
      value: ref(),
      type: 'input_search',
      width: 140,
    },
    {
      key: 'purchaseUname',
      label: '采购员',
      value: ref(),
      type: 'input_search',
      width: 140,
    },
    {
      type: 'keyword_date_range',
      key: 'gmtAudit',
      keyItems: [
        { label: '提交时间', value: 'gmtAudit' },
        { label: '接单时间', value: 'gmtAccept' },
      ],
      keyWidth: '100',
      value: ref(),
      placeholder: '请输入',
      label: '提交时间',
      width: 240,
      attrs: {
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        timePickerProps: { defaultValue: ['00:00:00', '23:59:59'] },
      },
    },
  ])
  const rowSelection = ref({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  }) as any
  let searchVal = ref<any>({
    pageSize: 20,
    pageNum: 1,
    status: '',
  })
  const settleAccounts = {
    1: '月结',
    2: '现货',
    3: '现款',
  }
  const showItemDetail = ref(false)
  const showDetail = ref(false)
  const tableLoading = ref(false)
  const showReceive = ref(false)
  const tableList = ref<Array<any>>([])
  const total = ref(0)
  const selectIds = ref([])
  const currentData = ref<any>({})

  const countMap = ref<any>({})
  const filterData = ref<any>({})
  const tableListref = ref()

  // 显示sku规格
  function getProductSpecs(item: any) {
    let productSpecs = item.productSpecs ? parseJson(item.productSpecs, []) : []
    return productSpecs.map((el: any) => el.valueCn)?.join('*') || '--'
  }

  // 通过条件查询列表
  function searchByVal(info: any) {
    searchVal.value.pageNum = 1
    filterData.value = JSON.parse(JSON.stringify(info)) || {}
    getTableList()
  }
  // 分页
  function changePage(val: number) {
    searchVal.value.pageNum = val
    getTableList()
  }
  function sizeChange(val: number) {
    searchVal.value.pageSize = val
    getTableList()
  }
  function selectColumn(val: any) {
    selectIds.value = val
  }
  // 切换状态
  function changeStatus(status: number | string) {
    searchVal.value.status = status
    searchVal.value.pageNum = 1
    getTableList()
  }
  // 查询列表和数量合计
  function getListAndCount() {
    getTableList()
    getCountList()
  }
  // 查询各状态下数量合计
  async function getCountList() {
    const res: any = await findPurchaseCountStatusBySupplier()
    let counts = res?.data || []
    countMap.value = {}
    counts.forEach((el: any) => {
      countMap.value[el.status] = el.totalCount
    })
  }
  // 获取商品列表
  async function getTableList() {
    tableList.value = []
    tableListref.value.selectAll(false)
    let params = {
      ...searchVal.value,
      ...filterData.value,
    }
    tableLoading.value = true
    const res: any = await findPurchaseBySupplierPage(params)
    tableLoading.value = false
    tableList.value = res?.data?.records || []
    total.value = res?.data?.total || 0
    expandable.value.expandedRowKeys = tableList.value.map((el: any) => el.id)
  }
  // 合并单元格
  function spanMethodAll(option: any) {
    let { column } = option
    if (column.dataIndex === 'img') {
      return { rowspan: 1, colspan: 15 }
    }
  }

  // 查看采购订单详情
  function toDetail(item: any) {
    currentData.value = item || {}
    showDetail.value = true
  }
  // 查看采购订单明细详情
  function toDetailItem(item: any) {
    currentData.value = item || {}
    showItemDetail.value = true
  }
  // 接单
  function openReceive(item: any) {
    currentData.value = item || {}
    showReceive.value = true
  }
</script>
<style lang="less" scoped>
  :deep(.arco-table-td) {
    background-color: var(--color-fill-1);
    height: auto;
  }
  :deep(.arco-table-tr-expand) {
    .arco-table-cell {
      padding: 0;
    }
    .arco-table {
      margin: 0 !important;
      .arco-table-td {
        border-bottom: 1px solid var(--color-neutral-3);
        height: 48px;
      }
    }
    background-color: #fff !important;
  }
  .price-type {
    font-size: 12px;
    transform: scale(0.82);
    position: relative;
    left: -4px;
  }
  :deep(.child-row) {
    .arco-table-cell {
      padding: 2px 8px;
    }
  }
  :deep(.arco-table-tr-expand .arco-table-td) {
    background-color: #fff !important;
    border-bottom: none;
  }
  :deep(.arco-table-tr-expand tr:hover .arco-table-td) {
    background-color: var(--color-fill-1) !important;
  }
  :deep(.arco-table-expand .arco-table-cell) {
    display: none;
  }
  :deep(.arco-tabs-nav-tab) {
    background-color: #fff;
  }
  .order-w {
    color: #666;
    flex: 1;
    .order-detail-item {
      width: 200px;
      padding-right: 5px;
    }
  }
  .urgent {
    font-size: 12px;
    display: inline-block;
    background-color: red;
    color: #fff;
    width: 18px;
    border-radius: 50%;
    line-height: 18px;
    text-align: center;
    transform: scale(0.82);
  }
</style>
